from PyQt5 import QtWidgets
from PyQt5.QtWidgets import QFileDialog, QWidget
import json, xlwt


class MyWindow(QWidget):
    def __init__(self):
        super(MyWindow, self).__init__()
        self.myButton = QtWidgets.QPushButton(self)
        self.myButton.setObjectName("btn")
        self.myButton.setText("按钮")
        self.myButton.clicked.connect(self.save_xls)
        self.txt = 'hellow'
        self.jso = ['hellow']
        self.xls = 'hellow'

    def save_txt(self):
        txt = self.txt
        filepath, type = QFileDialog.getSaveFileName(self, "文件保存", "/",
                                                     'txt(*.txt)')  # 前面是地址，后面是文件类型,得到输入地址的文件名和地址txt(*.txt*.xls);;image(*.png)不同类别
        file = open(filepath, 'w')
        print(filepath)
        file.write(txt)

    def save_json(self):
        jso = self.jso
        filepath, type = QFileDialog.getSaveFileName(self, '文件保存', '/', 'json(*.json)')
        print(filepath)
        with open(filepath, 'w') as file_obj:
            json.dump(jso, file_obj)

    def save_xls(self):
        xls = self.xls
        book = xlwt.Workbook(encoding='utf-8', style_compression=0)
        sheet = book.add_sheet('number', cell_overwrite_ok=True)
        sheet.write(0, 0, xls)
        filepath, type = QFileDialog.getSaveFileName(self, '文件保存', '/', 'xls(*.xls)')
        print(filepath)
        book.save(filepath)


if __name__ == "__main__":
    import sys

    app = QtWidgets.QApplication(sys.argv)
    myshow = MyWindow()
    myshow.show()
    sys.exit(app.exec_())